package com.fts.fts.fitness_tracking_system.controller;

import com.fts.fts.fitness_tracking_system.utils.JwtUtil;
import com.fts.fts.fitness_tracking_system.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


/**
 * 服务化 system模块 对外接口请求类
 */
@RestController
@RequestMapping("/sys")
public class SystemAPIController {


    @Value("${avatar.upload-dir}")
    private String uploadDir;

    @Value("${avatar.access-url}")
    private String accessUrlPrefix;

    @PostMapping("/files/uploadImages")
    public Result<?> uploadAvatar(
            @RequestParam("files") MultipartFile[] files,
            @RequestHeader("Authorization") String token) {

        List<String> accessUrlList = new ArrayList<>();
        try {
            // 1. Token验证
            if (!JwtUtil.validateToken(token)) {
                boolean validate = JwtUtil.validateToken(token);
                if (!validate) {
                    return new Result<>(401, "未授权");
                }
            }

            for (MultipartFile file : files) {
                // 2. 生成唯一文件名
                String originalFilename = file.getOriginalFilename();
                String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
                String newFilename = UUID.randomUUID() + fileExtension;

                // 3. 保存文件
                Path uploadPath = Paths.get(uploadDir);
                if (!Files.exists(uploadPath)) {
                    Files.createDirectories(uploadPath);
                }
                Path filePath = uploadPath.resolve(newFilename);
                Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
                String accessUrl = accessUrlPrefix + newFilename;
                accessUrlList.add(accessUrl);
            }

            return new Result<>(200, "上传成功",accessUrlList);
        } catch (IOException e) {
            return new Result<>(400, "文件存储失败");
        }
    }

}
